package com.quectel.util.spring;

import cn.hutool.core.text.CharSequenceUtil;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import javax.validation.Validator;

/**
 * 上下文帮助类
 *
 * @author cl
 */
public class SpringUtils {

    private static ApplicationContext applicationContext;


    private SpringUtils() {

    }

    /**
     * 获取上下文
     */
    public static ApplicationContext getContext() {
        return applicationContext;
    }

    /**
     * 设置上下文
     *
     * @param applicationContext
     */
    public static synchronized void setContext(ApplicationContext applicationContext) {
        if (SpringUtils.applicationContext != null) {
            return;
        }
        SpringUtils.applicationContext = applicationContext;
    }

    /**
     * 找不到bean会抛出异常
     *
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> tClass) {
        return applicationContext.getBean(tClass);
    }

    /**
     * 找不到bean会抛出异常
     *
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    public static boolean isDev() {
        return "dev".equals(applicationContext.getEnvironment().getActiveProfiles()[0]);
    }

    /**
     * 获取yml里边的值s
     *
     * @param key
     * @return
     */
    public static String getConfigValue(String key) {
        Environment environment = applicationContext.getEnvironment();
        return environment.getProperty(key);
    }

    /**
     * 获取参数校验器
     *
     * @return
     */
    public static Validator getValidator() {
        return getBean(Validator.class);
    }


    /**
     * 主动向Spring容器中注册bean
     *
     * @param obj 对象
     * @return 返回注册到容器中的bean对象
     */
    public static synchronized void registerSingleton(Object obj) {
        if (obj == null) {
            return;
        }
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
        beanFactory.registerSingleton(CharSequenceUtil.lowerFirst(obj.getClass().getSimpleName()), obj);
    }

    /**
     * 删除bean
     *
     * @param clazz clazz
     */
    public static synchronized void destroySingleton(Class<?> clazz) {
        //找不到bean抛出异常
        Object bean = getBean(clazz);

        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
        beanFactory.destroyBean(bean);
    }


}
